<template>
    <section class="app-upload-oss-img">
      <dl class="img-upload-content me-row">
        <dd class="item me-col-3" v-for="(item,index) in files" v-if="item.fileLocate==myFileLocate">
          <span class="iconfont icon-shanchu" @click="handleDelImg(index,item)"></span>
          <img v-if="showPopupImg" class="img" :src="item.src"/>
          <img v-else class="img" :src="item.src" @click="handleCheckPic(index)"/>
        </dd>
        <dd class="item me-col-3 item-add" @click="handleSelectImg(myFileLocate)">
          <span class="iconfont add-img icon-jiahao"></span>
        </dd>
      </dl>

      <!--图片大图弹窗-->
      <mt-popup
        v-model="popupSwiper"
        position="middle" class="me-popup-pic">
        <popup-swiper v-bind:picList="needPicList" @popupSwiperClose="popupSwiper=false"></popup-swiper>
      </mt-popup>
      <!--图片大图弹窗-->
    </section>
</template>

<script>
  import {Toast} from 'mint-ui';
  import wechatAuthorize from '../../common/wechat-authorize'
  import popupSwiper from '../common/popup-swiper';
  export default {
    props:{
      showPopupImg:'',
      oldFiles:[],
      myFileLocate:''
    },
    components:{
      popupSwiper,
    },
    data () {
      return {
        files:this.oldFiles,
        picList:[],
        picIndex:0,
        mediaAttr:this.oldFiles,
        accessToken:'',
        popupSwiper:false,
        needPicList:[],
      }
    },
    mounted(){

      /**调取微信配置接口**/
      wechatAuthorize.getWechatApi('chooseImage','uploadImage','getLocalImgData','downloadImage').then((data)=>{
        this.accessToken=data;
      this.$emit('getAccessToken',this.accessToken);
        }).catch(
            res => {
            console.log('error data::', res);}
        );
    },
    methods:{
      /** 选择图片**/
      handleSelectImg(myFileLocate){
          this.$wx.ready(()=>{

              /** 判断当前的手机环境**/
            var u = navigator.userAgent;
            var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
            var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

            var _this=this;
            var syncUpload = function(localIds){
              var localId = localIds.pop();
              _this.$wx.uploadImage({
                localId: localId.toString(), // 需要上传的图片的本地ID，由chooseImage接口获得
                isShowProgressTips: 1, // 默认为1，显示进度提示
                success: function (res) {
                  //res.serverId 返回图片的服务器端ID
                  const item={
                    serverId:res.serverId,
                    tag : '',
                    fileLocate:myFileLocate,
                  }
                  _this.mediaAttr.push(item);

                  _this.$emit('myMediaAttr',_this.mediaAttr)
                  if(localIds.length > 0){
                    window.setTimeout(function(){
                      syncUpload(localIds);
                    },100);
                  }else{
                    window.setTimeout(function(){
                      downloadImage(0);
                    },100);
                  }
                }
              })
            }

            /** 微信选择图片**/
            _this.$wx.chooseImage({
              count: 9, // 默认9
              sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
              sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
              defaultCameraMode: "batch", //表示进入拍照界面的默认模式，目前有normal与batch两种选择，normal表示普通单拍模式，batch表示连拍模式，不传该参数则为normal模式。（注：用户进入拍照界面仍然可自由切换两种模式）
              success: function (res) {

                var localIds = res.localIds; // 返回选定照片的本地ID列表，

                for(var i=0;i<localIds.length;i++){
                  if(isiOS==true){
                    _this.$wx.getLocalImgData({
                      localId: localIds[i], // 图片的localID
                      success: function (res) {
                        var localData = res.localData; // localData是图片的base64数据，可以用img标签显示
                        const item={
                          src:localData,
                          tag : '',
                          fileLocate:myFileLocate,
                        };
                        _this.files.push(item);
                      },
                      fail: function(res) {
                        console.log(res)
                      }
                    });
                  }else{
                    const item={
                      src:localIds[i],
                      tag : '',
                      fileLocate:myFileLocate,
                    };
                    _this.files.push(item);
                  }
                }
                syncUpload(res.localIds)
                // andriod中localId可以作为img标签的src属性显示图片；
                // 而在IOS中需通过上面的接口getLocalImgData获取图片base64数据，从而用于img标签的显示
              }
            });
        })
      },
      /** 删除图片**/
      handleDelImg(index,item){
        this.files.splice(index, 1);
        this.mediaAttr.splice(index, 1);
        this.$emit('myMediaAttr',this.mediaAttr);

        if(item.id!==undefined){
          var params = new URLSearchParams();
          params.append('form.uploadId',item.id);
          this.$axios({
            method: 'post',
            url:'gp/bu/ossUpload!deleteOssUpload.do',
            data:params
          }).then((res)=>{
            if(res.data.result==true && res.data.statusCode==200){
            Toast({
              message: res.data.message,
              position: 'middle',
              duration:600
            });
          }
        });
        }
      },
      /**查看大图**/
      handleCheckPic(type){
        this.needPicList=this.files;
        this.popupSwiper=true;
      },
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style scoped>
  .app-upload-oss-img{
    display: block;
    width: 100%;
  }
  .app-upload-oss-img .img-upload-content{
    width:94%;
    margin: 0;
    padding:0 0 16px;
  }
  .app-upload-oss-img .img-upload-content .item{
    position: relative;
    width:33.2% !important;
    height:60px;
    padding:0 12px 12px 0;
    margin:16px 0 0;
  }
  .app-upload-oss-img .img-upload-content img{
    width: 100%;
    height: 60px;
  }
  .app-upload-oss-img .img-upload-content .icon-shanchu{
    background:rgba(225,225,225,0.5) !important;
    position: absolute;
    top:0;
    right:12px;
    width: 20px;
    height: 20px;
    font-size:15px !important;
    color:#fff;
    text-align: center;
    line-height: 24px;
  }
  .app-upload-oss-img .add-img{
    display: block;
    height: 60px;
    padding:0;
    color: #ddd;
    line-height: 60px;
    text-align: center;
    border:1px dashed #ddd;
  }
  .app-upload-oss-img .add-img:before{
    display: block;
    margin:0 auto 4px;
    font-size: 24px;
  }
  .app-upload-oss-img .me-popup-pic{
    width: 100%;
    height:100%;
  }
  .app-upload-oss-img .me-popup-pic .mint-swipe,.app-upload-oss-img .me-popup-pic .mint-swipe-items-wrap{
    height: 100% !important;
  }
</style>
